package com.example.mobifin_busticket.views.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.models.SourceModel;
import com.example.mobifin_busticket.views.adapter.CustommenuListAdapter;
import com.example.mobifin_busticket.views.dialogs.CancelTicketDialog;
import com.example.mobifin_busticket.views.dialogs.Dialog_SelectDate;
import com.example.mobifin_busticket.views.dialogs.PrintTicketDialog;

public class SearchBusAcitivity extends MobifinActivity implements
		OnClickListener {
	Button btn_search_bus, btn_userSelectMenu;
	private LinearLayout llError, llChildError;
	public static TextView txt_source_city, txt_dest_city, txt_jorny_date,
			txt_errInFromCity, txt_errInToCity, txt_errInSameCity;
	ImageView img_calnder;
	private int year, month, day;
	String selectedDate, defaultDate;
	public static String formateDate;
	// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	String strSelectedSourceName, strSelectedDestinationName,
			strSelectedSourceID, strSelectedDestinationID;
	LinearLayout ll_selectSoruce, ll_select_Destination, llSelectDate;
	ListView MenuList;
	CustommenuListAdapter listAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_bus_acitivity);
		llError = (LinearLayout) findViewById(R.id.ll_error_on_searchBus);
		btn_userSelectMenu = (Button) findViewById(R.id.btn_userSelectMenu);
		llChildError = (LinearLayout) findViewById(R.id.ll_child_error_on_serachBus);
		txt_source_city = (TextView) findViewById(R.id.txt_enter_source);
		txt_dest_city = (TextView) findViewById(R.id.txt_enter_destination);
		txt_jorny_date = (TextView) findViewById(R.id.txt_Journey_date);
		btn_search_bus = (Button) findViewById(R.id.btn_search_bus);
		img_calnder = (ImageView) findViewById(R.id.img_calender);
		llSelectDate = (LinearLayout) findViewById(R.id.LL_Selectdate);
		ll_selectSoruce = (LinearLayout) findViewById(R.id.ll_SelectSource);
		ll_select_Destination = (LinearLayout) findViewById(R.id.ll_select_Destination);
		MenuList = (ListView) findViewById(R.id.menu_list);
		btn_userSelectMenu.setOnClickListener(this);
		txt_source_city.setOnClickListener(this);
		btn_search_bus.setOnClickListener(this);
		llSelectDate.setOnClickListener(this);
		img_calnder.setOnClickListener(this);
		ll_select_Destination.setOnClickListener(this);
		ll_selectSoruce.setOnClickListener(this);
		llError.setOnClickListener(this);

		ArrayList<String> listValue = new ArrayList<String>();
		listValue.add(getResources().getString(R.string.cancel_ticket));
		listValue.add(getResources().getString(R.string.print_ticket));
		listAdapter = new CustommenuListAdapter(SearchBusAcitivity.this,
				R.layout.custom_menu_list, listValue);
		MenuList.setAdapter(listAdapter);

		MenuList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				onMenuItemClick(position);
			}
		});
		ResponseListener listener = new ResponseListener() {

			@Override
			public void onResponse(Object object) {
				// TODO Auto-generated method stub
				ArrayList<SourceModel> sourceList = (ArrayList<SourceModel>) object;
				System.out.println("We are in activity:source list size is:"
						+ sourceList.size());
			}
		};

		BusTicketManagaer busticketManager = new BusTicketManagaer();

		busticketManager.getAllsources(SearchBusAcitivity.this, listener,
				AppData.CONSUMERKEY, AppData.SECRETKEY, AppData.BASESEATURL
						+ "/sources", "SOURCE");

		final Calendar c = Calendar.getInstance();
		long date = System.currentTimeMillis();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		SimpleDateFormat sdf = new SimpleDateFormat("EEE,dd MMM yyyy");
		String dateString = sdf.format(date);
		txt_jorny_date.setText(dateString);

		// formate date

		SimpleDateFormat formate_Date = new SimpleDateFormat("yyyy-MM-dd");
		formateDate = formate_Date.format(date);

	}

	protected void onMenuItemClick(int position) {
		// TODO Auto-generated method stub
		if (position == 0) {
			System.out.println("on click Cancle");
			CancelTicketDialog dialog = new CancelTicketDialog(
					SearchBusAcitivity.this);
			dialog.show();
			Util.mListHide(MenuList);
		}
		if (position == 1) {
			System.out.println("on click print");
			PrintTicketDialog pdialog = new PrintTicketDialog(
					SearchBusAcitivity.this);
			pdialog.show();
			Util.mListHide(MenuList);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ll_SelectSource:
		case R.id.txt_enter_source:
			Util.mListHide(MenuList);
			onClickSourceCity();
			break;

		case R.id.ll_select_Destination:
		case R.id.txt_enter_destination:
			Util.mListHide(MenuList);
			onClickDestinationCity();
			break;

		case R.id.LL_Selectdate:
			Util.mListHide(MenuList);
			onClickDate();
			break;
		case R.id.ll_error_on_searchBus:
			Util.mListHide(MenuList);
			llError.setVisibility(View.GONE);
			break;
		case R.id.btn_search_bus:
			Util.mListHide(MenuList);
			onClickSearchBus();
			break;
		case R.id.btn_userSelectMenu:
			Util.onClickUserMenu(SearchBusAcitivity.this, MenuList);
			break;
		default:
			break;
		}
	}

	private void onClickSearchBus() {
		// TODO Auto-generated method stub
		if (validateFields()) {
			llError.setVisibility(View.GONE);
			String from_city = txt_source_city.getText().toString();
			String to_city = txt_dest_city.getText().toString();
			String journy_date = txt_jorny_date.getText().toString();

			Intent select_bus_trip = new Intent(SearchBusAcitivity.this,
					AvailableTripsActivity.class);
			select_bus_trip.putExtra("From", from_city);
			select_bus_trip.putExtra("SouceID", strSelectedSourceID);
			select_bus_trip.putExtra("To", to_city);
			select_bus_trip.putExtra("DestinationID", strSelectedDestinationID);
			select_bus_trip.putExtra("DOJ", formateDate);
			select_bus_trip.putExtra("jdate", journy_date);
			startActivity(select_bus_trip);
		}

	}

	private void onClickDate() {
		// TODO Auto-generated method stub
		Dialog_SelectDate cal = new Dialog_SelectDate(SearchBusAcitivity.this);
		cal.show();
		formateDate = cal.formate_date();
	}

	private void onClickSourceCity() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(SearchBusAcitivity.this,
				SelectSourceCityActivity.class);
		intent.putExtra("FOR", "Source");
		startActivityForResult(intent, 1);
		overridePendingTransition(R.anim.pull_up_from_bottom, R.anim.hold);

	}

	private void onClickDestinationCity() {
		// TODO Auto-generated method stub
		Intent Dest_intent = new Intent(SearchBusAcitivity.this,
				SelectDestinationCityActivity.class);
		Dest_intent.putExtra("FOR", "Destination");
		startActivityForResult(Dest_intent, 2);
		overridePendingTransition(R.anim.pull_up_from_bottom, R.anim.hold);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK && requestCode == 1) {

			strSelectedSourceName = data.getStringExtra("resultName");
			strSelectedSourceID = data.getStringExtra("resultID");

			txt_source_city.setText(strSelectedSourceName);

			getDestinations(strSelectedSourceID);
		}
		if (resultCode == RESULT_OK && requestCode == 2) {

			strSelectedDestinationName = data.getStringExtra("DresultName");
			strSelectedDestinationID = data.getStringExtra("DresultID");
			txt_dest_city.setText(strSelectedDestinationName);

		}

	}

	private void getDestinations(String sourceID) {
		// TODO Auto-generated method stub
		txt_dest_city.setOnClickListener(this);
		ResponseListener fetchDestination = new ResponseListener() {

			@Override
			public void onResponse(Object object) {
				// TODO Auto-generated method stub
				ArrayList<SourceModel> destiantions = (ArrayList<SourceModel>) object;
				System.out
						.println("We are in activity:Destinaation list size is:"
								+ destiantions.size());
				// txt_dest_city.setText(destiantions.get(0).getName());
				AppData.list = destiantions;

			}
		};

		BusTicketManagaer busticketManager = new BusTicketManagaer();

		busticketManager.getDestination(SearchBusAcitivity.this,
				fetchDestination, AppData.CONSUMERKEY, AppData.SECRETKEY,
				AppData.BASESEATURL + "/destinations?source=" + sourceID,
				"SOURCE");
	}

	private boolean validateFields() {
		return conditionForSourceDestinationempty();
	}

	private boolean conditionForSourceDestinationempty() {
		Animation slide = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slidedown);
		boolean isValidate = false;
		int noofField = 0;
		String errorMessage = "";

		if (txt_source_city.getText().toString()
				.equals(getResources().getString(R.string.city_name))
				&& txt_dest_city.getText().toString()
						.equals(getResources().getString(R.string.city_name))) {
			llError.startAnimation(slide);
			llError.setVisibility(View.VISIBLE);
			noofField = 3;
			errorMessage = getResources().getString(
					R.string.bus_seerchbus_forget_title)
					+ ":"
					+ getResources().getString(R.string.err_from_city)
					+ ":" + getResources().getString(R.string.err_To_city);
			Util.errorFieldcreationSeatselect(SearchBusAcitivity.this,
					llChildError, noofField, errorMessage);
			isValidate = false;
		} else if (txt_source_city.getText().toString()
				.equals(getResources().getString(R.string.city_name))) {
			llError.startAnimation(slide);
			llError.setVisibility(View.VISIBLE);
			noofField = 2;
			errorMessage = getResources().getString(
					R.string.bus_seerchbus_forget_title)
					+ ":"
					+ getResources().getString(R.string.err_from_city)
					+ ":" + " ";
			Util.errorFieldcreationSeatselect(SearchBusAcitivity.this,
					llChildError, noofField, errorMessage);
			isValidate = false;
		} else if (txt_dest_city.getText().toString()
				.equals(getResources().getString(R.string.city_name))) {
			llError.startAnimation(slide);
			llError.setVisibility(View.VISIBLE);
			noofField = 2;
			errorMessage = getResources().getString(
					R.string.bus_seerchbus_forget_title)
					+ ":"
					+ getResources().getString(R.string.err_To_city)
					+ ":" + " ";
			Util.errorFieldcreationSeatselect(SearchBusAcitivity.this,
					llChildError, noofField, errorMessage);
			isValidate = false;
		} else if (!txt_source_city.getText().toString()
				.equals(getResources().getString(R.string.city_name))
				&& !txt_source_city.getText().toString()
						.equals(getResources().getString(R.string.city_name))
				&& txt_source_city.getText().toString()
						.equals(txt_dest_city.getText().toString())) {
			llError.startAnimation(slide);
			llError.setVisibility(View.VISIBLE);
			noofField = 2;
			errorMessage = getResources().getString(
					R.string.bus_seerchbus_forget_title)
					+ ":"
					+ getResources().getString(R.string.bus_seerchbus_err_same)
					+ ":" + " ";
			Util.errorFieldcreationSeatselect(SearchBusAcitivity.this,
					llChildError, noofField, errorMessage);
			isValidate = false;
		} else {
			llError.setVisibility(View.GONE);
			isValidate = true;
		}
		return isValidate;

	}
}
